package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * Author 喵喵喵
 * Date 2025/6/6 9:01
 */
@Aspect
@Component
public class AutoFillAspect {

    /**
     * @param joinPoint
     * @throws Throwable
     */
    @Before("@annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint) {
        //1.获取需要增强的方法,判断他是新增还是修改
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType type = autoFill.value();

        Object[] args = joinPoint.getArgs();
        Object entity=args[0];

        LocalDateTime now = LocalDateTime.now();
        Long empId = BaseContext.getCurrentId();
        //2.判断类型type是否为新增
        if (type == OperationType.INSERT) {

            Class clazz = entity.getClass();
            try {
                Method setCreateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                setCreateTime.invoke(entity, now);
                Method setUpdateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setUpdateTime.invoke(entity, now);
                Method setCreateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                setCreateUser.invoke(entity, empId);
                Method setUpdateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateUser.invoke(entity, empId);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        } else {
            Class clazz = entity.getClass();
            //给两个属性赋值
            try {
            Method setUpdateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateTime.invoke(entity, now);
            Method setUpdateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateUser.invoke(entity, empId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }


    }
}
